// Author: wsfuyibing <682805@qq.com>
// Date: 2025-06-13

package scan

import (
	"context"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/errs"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/lib"
)

// Logic
// 扫码回鱼.
type Logic struct {
	arcade   *models.Arcades
	request  *Request
	response *Response
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: NewResponse(),
	}
}

// Before
// 前置校验.
func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	if err = validator.Query(i, o.request); err == nil {
		o.arcade, _ = lib.Arcade.GetMaster().GetArcade(i)
	}
	return
}

// Run
// 执行逻辑.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		err  error
		has  bool
		res  = result.New()
		user *models.Users
	)

	// 1. 读取用户.
	if user, has, err = services.NewUsersService().Dao.GetById(ctx, o.request.Id); err != nil {
		return res.WithError(errs.ErrDatabaseQuery)
	}

	// 2. 无效用户.
	//    用户不存在或状态错误.
	if !has || !user.State.IsNormal() {
		return res.WithError(errs.ErrUserNotFound)
	}

	// 3. 用户有效.
	o.response.WithUser(user)

	// 3.1 用户渔票.
	if err = o.RunRecord(ctx); err != nil {
		return res.WithError(err)
	}

	// 3.2 会员服务.
	if err = o.RunMember(ctx); err != nil {
		return res.WithError(err)
	}

	// 4. 返回结果.
	return res.With(o.response)
}

// RunMember
// 构建会员.
func (o *Logic) RunMember(ctx context.Context) (err error) {
	var (
		has     bool
		member  *models.ArcadeMember
		setting *models.ArcadeSetting
	)

	// 1. 读取设置.
	if setting, has, err = services.NewArcadeSettingService().Dao.GetByMap(ctx, map[string]any{
		"arcade_id": o.arcade.Id,
	}); err != nil {
		err = errs.ErrDatabaseQuery
		return
	}

	// 2. 设置选项.
	if !has {
		err = errs.ErrArcadeSettingNotFound
		return
	}

	// 3. 会员配置.
	//    钓场开启了高价回鱼.
	if !setting.MemberReturnEnabled.IsYes() {
		return
	} else {
		o.response.WithSetting(setting)
	}

	// 4. 会员信息.
	if member, has, err = services.NewArcadeMemberService().Dao.GetByMap(ctx, map[string]any{
		"arcade_id": o.arcade.Id,
		"user_id":   o.request.Id,
	}); err != nil {
		err = errs.ErrDatabaseQuery
		return
	} else if has {
		o.response.WithMember(member)
	}
	return
}

// RunRecord
// 渔票列表.
func (o *Logic) RunRecord(ctx context.Context) (err error) {
	var (
		lr  []*models.TicketRecord
		cid = make([]int64, 0)
		sid = make([]int64, 0)
		tid = make([]int64, 0)
	)

	// 1. 读取列表.
	//    指定用户在指定日期的购票列表.
	if lr, err = services.NewTicketRecordService().Dao.ListByMap(ctx, map[string]any{
		"arcade_id": o.arcade.Id,
		"user_id":   o.request.Id,
		"date":      o.request.Date,
	}); err != nil {
		err = errs.ErrDatabaseQuery
		return
	}

	// 2. 创建列表.
	for _, r := range lr {
		// 2.1 隶属渔票
		if r.TicketId > 0 {
			tid = append(tid, r.TicketId)
		}
		// 2.2 隶属场次.
		if r.SessionId > 0 {
			sid = append(sid, r.SessionId)
		}
		// 2.3 选中钓位.
		if r.SeatId > 0 {
			cid = append(cid, r.SeatId)
		}
		// 2.4 加入记录.
		o.response.AddRecord(r)
	}

	// 3. 绑定场次.
	if len(sid) > 0 {
		if err = o.RunRecordSession(ctx, sid); err != nil {
			return
		}
	}

	// 4. 绑定渔票.
	if len(tid) > 0 {
		if err = o.RunRecordTicket(ctx, tid); err != nil {
			return
		}
	}

	// 5. 绑定钓位.
	if len(cid) > 0 {
		if err = o.RunRecordSeat(ctx, cid); err != nil {
			return
		}
	}

	// 6. 绑定完成.
	return
}

// RunRecordSeat
// 钓位绑定.
func (o *Logic) RunRecordSeat(ctx context.Context, ids []int64) (err error) {
	var mapper = make(map[int64]*models.ArcadePondSeat)

	if mapper, err = services.NewArcadePondSeatService().MapByIdList(ctx, ids); err != nil {
		err = errs.ErrDatabaseQuery
		return
	}

	for _, v := range o.response.Records {
		if v.SeatId > 0 {
			if s, ok := mapper[v.SeatId]; ok {
				v.WithSeat(s)
			}
		}
	}
	return
}

// RunRecordSession
// 场次绑定.
func (o *Logic) RunRecordSession(ctx context.Context, ids []int64) (err error) {
	var mapper = make(map[int64]*models.TicketSession)

	if mapper, err = services.NewTicketSessionService().MapByIdList(ctx, ids); err != nil {
		err = errs.ErrDatabaseQuery
		return
	}

	for _, v := range o.response.Records {
		if v.SessionId > 0 {
			if s, ok := mapper[v.SessionId]; ok {
				v.WithSession(s)
			}
		}
	}

	return
}

// RunRecordTicket
// 鱼票绑定.
func (o *Logic) RunRecordTicket(ctx context.Context, ids []int64) (err error) {
	var mapper = make(map[int64]*models.Ticket)

	if mapper, err = services.NewTicketService().MapByIdList(ctx, ids); err != nil {
		err = errs.ErrDatabaseQuery
		return
	}

	for _, v := range o.response.Records {
		if v.TicketId > 0 {
			if s, ok := mapper[v.TicketId]; ok {
				if v.Session != nil {
					v.Session.WithTicket(s)
				}
			}
		}
	}

	return
}
